package top.leyi.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import top.leyi.ServiceImpl.TokenServiceImpl;
import top.leyi.exception.WXLoginException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @descripe
 * 微信小程序登陆 获取用户唯一标识 openid，流程详情 https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
 * @author Allen
 * @date 19/06/14
 */
// appid wx5d49d43e53b389f5 secret e379aa912f650e8d54d0e9f002a797f7

@Component
@ConfigurationProperties(prefix = "wx")
public class HttpClientUtil {

    static final Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);
    private static String appid = "wx87e0647ad3dfa5af";
    private static String secret = "e379aa912f650e8d54d0e9f002a797f7";
    private static String grant_type = "authorization_code";

    public  static JSONObject sendGet(String url, Map<String, String> params){
        HttpEntity entity = null;
        String result = "error";
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                if(params != null && params.size() > 0){
                    url += "?";

                Set<Map.Entry<String, String>> entry = params.entrySet();
                for(Map.Entry e : entry){
                    url = url + "&" + e.getKey() + "=" +e.getValue();
                }
                }
                HttpGet httpGet = new HttpGet(url);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                entity = response.getEntity();
                byte[] bs =  EntityUtils.toByteArray(entity);
                result = new String(bs);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject json = new JSONObject(result);
        return json;
    }


    /*
     微信登陆代码示例
     */

    public static String WXLogin(String code) throws WXLoginException{


        Map<String, String> map = new HashMap<>();
        map.put("appid",  appid);
        map.put("secret",  secret);
        map.put("js_code", code);
        map.put("grant_type",  grant_type);

        JSONObject result  =  sendGet(
                "https://api.weixin.qq.com/sns/jscode2session", map);

        String openId = "";
        try{

            openId = String.valueOf(result.get("openid"));
            return   openId;

        }catch (Exception e){
           logger.error(e.toString());
           throw  new WXLoginException(String.valueOf(result.get("errmsg")));
        }

    }
    public static void main(String[] args)throws  IOException{

    }
}

